#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime

# Additional services for communication, like broadcast and virtual
# ring. It does not substitute the checkpoint protocol or
# communication channel, just provide extra services.

class virtualring(object):
    def __init__(self):
        self.comm_ = None
        self.pid_ = None
        self.hosts_ = None
        
    def set_comm(self, comm):
        self.comm_ = comm
        self.pid_ = self.comm_.get_pid()
        hosts = self.comm_.get_hosts()
        upper = [i for i in hosts if i > self.pid_] 
        lower = [i for i in hosts if i < self.pid_] 
        upper.sort()
        lower.sort()
        self.hosts_ = upper + lower

    def get_next(self):
        return self.get_pos(0)
    
    def get_prev(self):
        return self.get_pos(-1)

    def get_pos(self, pos):
        return self.hosts_[pos]

    def send_next(self, msg):
        self.send_pos(0, msg)

    def send_prev(self, msg):
        self.send_pos(-1, msg)

    def send_pos(self, pos, msg):
        self.comm_.send_message(self.hosts_[pos], msg)

class timer(object):
    def __init__(self, comm, datetime=datetime):
        self.comm = comm
        self.pck = datetime.datetime
        self.initial_time = self.pck.now()

    def send_timestamp(self):
        td = self.pck.now() - self.initial_time
        td *= 100
        dif = td.seconds + td.days * 86400
        dif /= 100.0
        self.comm.print_output('%.2f' % (dif))
    
        
